package cn.zjh.user.service.impl;

import cn.zjh.basic.constant.VerifyCodeConstants;
import cn.zjh.basic.exception.BusinessException;
import cn.zjh.basic.jwt.JwtUtils;
import cn.zjh.basic.jwt.LoginData;
import cn.zjh.basic.jwt.RsaUtils;
import cn.zjh.basic.service.impl.BaseServiceImpl;
import cn.zjh.basic.util.AjaxResult;
import cn.zjh.basic.util.HttpUtil;
import cn.zjh.basic.util.MD5Utils;
import cn.zjh.basic.util.StrUtils;
import cn.zjh.system.domain.Menu;
import cn.zjh.user.constant.WxConstants;
import cn.zjh.user.domain.Logininfo;
import cn.zjh.user.domain.User;
import cn.zjh.user.domain.Wxuser;
import cn.zjh.user.dto.BinderDto;
import cn.zjh.user.dto.LoginDto;
import cn.zjh.user.mapper.LogininfoMapper;
import cn.zjh.user.mapper.UserMapper;
import cn.zjh.user.mapper.WxuserMapper;
import cn.zjh.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登陆
     * @param loginDto
     * @return
     */
    @Override
    public Map<String,Object> accountLogin(LoginDto loginDto) {

        String account = loginDto.getAccount();
        String password = loginDto.getPassword();
        String loginType = loginDto.getLoginType();
        //校检数据是否为空
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password) || StringUtils.isEmpty(loginType)) {
            throw new BusinessException("数据不能为空");
        }

        Logininfo logininfo = logininfoMapper.findOneAccount(loginDto);

        if(logininfo == null){
            throw new BusinessException("账号或者密码错误！！");
        }
        //给账号或者密码加盐加密
        String dbmd5pwd = logininfo.getPassword();
        String md5pwd = MD5Utils.encrypByMd5(password + logininfo.getSalt());

        if(!dbmd5pwd.equals(md5pwd)){
            throw new BusinessException("账号或者密码错误！！");
        }

        if(!logininfo.getDisable()){
            throw new BusinessException("你的账号被冻结，请联系管理员!!!");
        }

       /* //将token和登录信息对象 保存在 redis 30分钟有效
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //使用Map将token和登录对象绑定到AjaxResult的resultObj中响应给前端
        //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        System.out.printf("================================================="+map);

        return map;

    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            //1.获取logininfo
            if(logininfo.getType()==0){//管理员
                //2.获取当前登陆人的所有权限 - sn
                List<String> permissions = logininfoMapper.loadPermissionsByLogininfoId(logininfo.getId());
                //3.获取当前登陆人的所有菜单 - 【难度】
                List<Menu> menus = logininfoMapper.loadMenusByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);

                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            //4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 3000);

            //5.装到map返回
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 微信扫码登录
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {

        String url = WxConstants.GET_ACK_URL
                .replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        String jsonStr = HttpUtil.httpGet(url);
    //    System.out.println(jsonStr+"---------------------------------");

        //将获取的字符串转换成json格式的字符串
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //通过opentid去t_wxuser中查询
       Wxuser wxuser = wxuserMapper.findOneOpenid(openid);
        //如果已经绑定过
       if (wxuser != null && wxuser.getUserId() != null){

           Logininfo logininfo = logininfoMapper.loadLogininfoByUserId(wxuser.getUserId());

           //将token和登录信息对象 保存在 redis 30分钟有效
           /*String token = UUID.randomUUID().toString();

           redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

           //使用Map将token和登录对象绑定到AjaxResult的resultObj中响应给前端
           //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名
           Map<String,Object> map = new HashMap<>();
           map.put("token",token);
           logininfo.setSalt(null);
           logininfo.setPassword(null);
           map.put("logininfo",logininfo);*/

           Map<String, Object> map = loginSuccessJwtHandler(logininfo);

           return AjaxResult.me().setResultObj(map);
       }else {
            //没有绑定就去绑定页面绑定
           Map<String,Object> map = new HashMap<>();
           map.put("access_token",access_token);
           map.put("openid",openid);
           return AjaxResult.me().setSuccess(false).setResultObj(map);

       }
    }

    /**
     * 手机绑定
     * @param binderDto
     * @return
     */
    @Override
    public AjaxResult binderLogin(BinderDto binderDto) {
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accessToken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();
        //校检数据是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("数据不能为空");
        }

        //校检验证码是否过期
        Object redisCode = redisTemplate.opsForValue().get(VerifyCodeConstants.BINDER_CODE_PREFIX +phone);
        if (redisCode==null){
            throw new BusinessException("验证码已失效^-^");
        }

        Object redisCodes = (redisCode.toString().split(":")[0]);
        //校检验证码是否正确
        if (!redisCodes.toString().equals(verifyCode)){
            throw new BusinessException("验证码错的离谱O_O");
        }

        //绑定用户：t_wxuser【user_id】绑定
        //获取wxuser 发送第三个请求，json字符串
        String Url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);
        String jsonStr = HttpUtil.httpGet(Url);

        System.out.println(Url+"url++++++++++++++++++++++++++");
        System.out.println(jsonStr+"jsonStr----------------------------");

        Wxuser wxuser = jsonStr2Wxuser(jsonStr);//userid//
       // Wxuser{, openid=null, nickname=null, sex=null, address=nullnullnull, headimgurl=null, unionid=null, userId=null}
        //根据手机号查找user用户
        User user = userMapper.findOnePhone(phone);

        System.out.println(wxuser+"微信用户]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");

        System.out.println(user+"user用户[[================================");

        //判断有咩有，没有就跟据手机号创建user对象，创建logininfo对象，保存user和logininfo对象
        if (user == null){
            user = phone2User(phone);
            Logininfo logininfoTmp= user2Logininfo(user);

            logininfoMapper.save(logininfoTmp);
            user.setLogininfoId(logininfoTmp.getId());
            userMapper.save(user);
        }

        //将User对象的id设置到WxUser对象中
        wxuser.setUserId(user.getId());
        //将WxUser对象添加到数据库
        wxuserMapper.save(wxuser);

        //8.做免密登录
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());

        /*String token = UUID.randomUUID().toString();
        //去掉密码和盐值 - 安全
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);*/

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    /**
     * 前台账号退出
     * @param token
     */
    @Override
    public void logOut(String token) {
        redisTemplate.delete(token);

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        //获取前端用户扫码授权获得的信息添加到数据库
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;//返回数据到wxuser对象
    }

}
